package com.jinzo.mporaba.tasks;

import java.util.ArrayList;

import com.jinzo.mporaba.DBAdapter;
import com.jinzo.mporaba.Mporaba;
import com.jinzo.mporaba.QuotaItem;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.Handler;

public class SaveToCPTask implements Runnable {;
	private Context context;
	private ArrayList<QuotaItem> m_items = new ArrayList<QuotaItem>();
	private Handler callback;
	
	public SaveToCPTask() {
	}
	public void load(Context context, ArrayList<QuotaItem> m_items, Handler callback) {
		this.context = context;
		this.m_items = m_items;
		this.callback = callback;
		
		Thread thread = new Thread(this);
		thread.setDaemon(true);
	    thread.start();
	}
	
    public void run() {
    	ContentResolver cr = context.getContentResolver();
    	Cursor first = cr.query(QuotaItem.CONTENT_URI, null, "_ID = 1", null, null); // Fragile probably
    	ContentValues values = new ContentValues();
    	if (first.getCount() == 0) {
    		// We need to insert
    		for (QuotaItem q : m_items) {
    			values.clear();
    			values.put(DBAdapter.KEY_DISPLAYNAME, q.getDisplayName());
    			values.put(DBAdapter.KEY_PREPAID, q.isPrepaid());
    			values.put(DBAdapter.KEY_UNIT, q.getUnit());
    			values.put(DBAdapter.KEY_AVAILABLE, q.getAvailable());
    			values.put(DBAdapter.KEY_USED, q.getUsed());
    			context.getContentResolver().insert(QuotaItem.CONTENT_URI, values);
    			//Log.i("SaveToCPTask", "Inserted entries");
    		}
    	} else {
    		// We need to update
    		for (QuotaItem q : m_items) {
    			values.clear();
    			values.put(DBAdapter.KEY_DISPLAYNAME, q.getDisplayName());
    			values.put(DBAdapter.KEY_PREPAID, q.isPrepaid());
    			values.put(DBAdapter.KEY_UNIT, q.getUnit());
    			values.put(DBAdapter.KEY_AVAILABLE, q.getAvailable());
    			values.put(DBAdapter.KEY_USED, q.getUsed());
    			if (context.getContentResolver().update(QuotaItem.CONTENT_URI, values, DBAdapter.KEY_DISPLAYNAME + "= \"" + q.getDisplayName() +"\"", null) != 1) {
    				//Log.w("SaveToCPTask", "Error while updating the content values, one UPDATE clouse updated more entries.");
    			} else {
    				//Log.i("SaveToCPTask", "Updated entries");
    			}
    		}	
    	}
    	first.close();
    	callback.sendEmptyMessage(Mporaba.REQUEST_SUCCESS);
    }
}
